package com.yoshino.leetcode.improve40.tenth;

import java.util.*;

class RandomizedSet {

    Map<Integer, Integer> maps;
    List<Integer> list;
    Random random;

    /**
     * Initialize your data structure here.
     */
    public RandomizedSet() {
        // 数组 和 HashMap
        // 数组：插入O(1)，删除：需要直接找到下标才可满足，查找问题
        // 哈希表：查找，value 标记 数组下标
        maps = new HashMap<>();
        list = new ArrayList<>();
        random = new Random();
    }

    /**
     * Inserts a value to the set. Returns true if the set did not already contain the specified element.
     */
    public boolean insert(int val) {
        if (maps.containsKey(val)) {
            return false;
        }
        list.add(val);
        maps.put(val, list.size() - 1);
        return true;
    }

    /**
     * Removes a value from the set. Returns true if the set contained the specified element.
     */
    public boolean remove(int val) {
        if (!maps.containsKey(val)) {
            return false;
        }
        // 需要将最后的值替换掉需要删除掉的值，防止下标前移
        int changeInd = maps.get(val);
        int rem = list.get(list.size() - 1);
        // 最外层
        list.set(changeInd, rem);
        list.remove(list.size() - 1);
        maps.put(rem, changeInd);
        maps.remove(val);
        return true;
    }

    /**
     * Get a random element from the set.
     */
    public int getRandom() {
        return list.get(random.nextInt(list.size()));
    }
}